package com.yonyou.pmclouds.enterprise.process;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.bp.template.MultiDeleteBpTemplate;
import com.yonyou.pmclouds.basecom.bp.template.MultiInsertBpTemplate;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.etpandorg.entity.EtpAndOrgVO;
import com.yonyou.pmclouds.etpandorg.mapper.EtpAndOrgMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author chulf
 * @Date 2020/4/15
 * @Description 添加完企业后维护组织关系
 **/
@Component
public class InsertOrgAfterProcess implements SingleProcessor<EnterpriseVO>, MultiProcessor<EnterpriseVO> {

    @Autowired
    private EtpAndOrgMapper etpAndOrgMapper;

    @Override
    public void process(EnterpriseVO vo, EnterpriseVO orig) throws BusinessException {
        if (orig != null) {
            //先把之前维护的组织关系删除
            EtpAndOrgVO etpAndOrgVO = new EtpAndOrgVO();
            etpAndOrgVO.setPkEnterprise(vo.getPkEnterprise());
            List<EtpAndOrgVO> etpAndOrgVOS = etpAndOrgMapper.get(etpAndOrgVO);
            if (etpAndOrgVOS != null && !etpAndOrgVOS.isEmpty()) {
                MultiDeleteBpTemplate<EtpAndOrgVO> bp = new MultiDeleteBpTemplate<>(etpAndOrgMapper, false);
                bp.delete(etpAndOrgVOS.toArray(new EtpAndOrgVO[0]));
            }
        }

        insertOrgInfo(new EnterpriseVO[]{vo});
    }

    @Override
    public void process(EnterpriseVO[] vos, EnterpriseVO[] origs) throws BusinessException {
        insertOrgInfo(vos);
    }

    private void insertOrgInfo(EnterpriseVO[] vos) throws BusinessException {
        if(vos == null || vos.length <= 0){
            return;
        }

        //添加新的组织关系
        List<EtpAndOrgVO> insertOrgList = new ArrayList<>();

        for(EnterpriseVO enterpriseVO : vos){
            List<String> pkOrgList = enterpriseVO.getPkOrgs();
            if(pkOrgList == null || pkOrgList.size() <= 0){
                continue;
            }

            for(String pkOrg : pkOrgList){
                EtpAndOrgVO tempVO = new EtpAndOrgVO();
                tempVO.setPkEnterprise(enterpriseVO.getPkEnterprise());
                tempVO.setPkOrg(pkOrg);
                insertOrgList.add(tempVO);
            }

        }

        if(insertOrgList.size() <= 0){
            return;
        }

        MultiInsertBpTemplate<EtpAndOrgVO> bp = new MultiInsertBpTemplate<>(etpAndOrgMapper);
        bp.insert(insertOrgList.toArray(new EtpAndOrgVO[0]));
    }
}
